import {
  throttle,
  formatTime
} from '../../utils/util'
import websocket from '../../utils/socket'
import customerApi from '../../utils/customerApi' // 引入api接口管理文件
import api from '../../utils/api'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    talkList: [],
    needLogin: true,
    imuid: 0,
    privacyData: {},
    bindMobile: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},
  onShow() {
    app.globalData.currentPage = 'customerList' // 全局设置当前页
    wx.hideTabBarRedDot({
      index: 1
    })
    this.init()
    websocket({}, (res) => {
      let data = JSON.parse(res)
      console.log('WebSocket customerList ===>', res);
      if (data.msg && Object.keys(data.msg).length > 0 && app.globalData.currentPage !== 'customerIntelligent') {
        this.init()
      }
    })
  },
  onHide() {
    this.setData({
      privacyData: {}
    })
  },
  init() {
    this.setData({
      needLogin: wx.getStorageSync('token') === '' ? true : false,
      imuid: wx.getStorageSync('imuid'),
      bindMobile: wx.getStorageSync('bindMobile')
    })
    this.conversationGet();
    this.getShowPrivacy();
  },
  onPullDownRefresh() {
    wx.hideTabBarRedDot({
      index: 1
    })
    this.conversationGet()
  },

  conversationGet() {
    const that = this

    wx.showLoading({
      title: '加载中...',
    })
    customerApi.conversationGet({
      data: {},
      success: res => {
        if (res.code * 1 === 0) {
          if (res.data.length * 1 === 0) {
            customerApi.messageCompany({
              data: {},
              success: res => {
                if (res.code * 1 === 0) {
                  that.conversationGet()
                }
              }
            })
            return
          }
          let data = res.data
          wx.hideLoading({
            success: (res) => {
              console.log(res)
            }
          })
          data.forEach(item => {
            item.showTime = formatTime(item.last_message_time)
          })
          this.setData({
            talkList: res.data
          }, () => {
            wx.stopPullDownRefresh()
          })
        }
      }
    })
  },
  moveTo(e) {
    const {
      index
    } = e.currentTarget.dataset
    app.globalData.customerChoose = this.data.talkList[index]
    throttle(function (e) {
      wx.navigateTo({
        url: `../customerIntelligent/index`
      })
    }, 2000)
  },
  closeModal() {
    this.setData({
      needLogin: false,
      bindMobile: true
    })
    this.conversationGet()
  },
  getShowPrivacy() {
    api.showPrivacy({
      data: {
        source: 2, // 1、app    2、小程序
      },
      success: (res) => {
        if (+res.code === 0) {
          this.setData({
            privacyData: res.data
          })
        }
      }
    })
  },

  onClosePrivacy() {
    const {
      privacyData
    } = this.data || {};
    privacyData.show = false
    this.setData({
      privacyData
    })
  },
})